//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
#pragma once
#include "precomp.h"



LPCWSTR CreateNewGuid()
{
    GUID guid; 
    static wchar_t wstrGuid[37];
    ::wmemset(wstrGuid, 0, 37);
    if (S_OK == ::CoCreateGuid(&guid))
    {     
        swprintf_s(wstrGuid, L"%08X-%04X-%04x-%02X%02X-%02X%02X%02X%02X%02X%02X",
            guid.Data1   , guid.Data2   , guid.Data3 , 
            guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], 
            guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7] );
    }
    return wstrGuid;
}

HRESULT GetEncoderClsid(CLSID* pClsid)
{ 
    UINT  uNumber = 0;  // number of image encoders
    UINT  uSize   = 0;  // size of the image encoder array in bytes
    HRESULT hr = S_FALSE; 
    GetImageEncodersSize(&uNumber, &uSize);
    if(uSize == 0) {
        return S_FALSE;  // Failure
    }
    ImageCodecInfo* pImageCodecInfo = (ImageCodecInfo*)(malloc(uSize));
    if(pImageCodecInfo == NULL) {
        return S_FALSE;  // Failure
    }
    GetImageEncoders(uNumber, uSize, pImageCodecInfo);
    for(UINT uIndex = 0; uIndex < uNumber; ++uIndex)
    {
        if(wcscmp(pImageCodecInfo[uIndex].MimeType, L"image/bmp") == 0 )
        {
            *pClsid = pImageCodecInfo[uIndex].Clsid;
            free(pImageCodecInfo);
            return S_OK;  // Success
        }
    } 
    free(pImageCodecInfo);
    return S_FALSE;  // Failure
}


HRESULT SaveImage(Image* img)
{
    HRESULT hr = S_FALSE; 
    if(img == NULL)
    {
        return hr;
    }
    CLSID imgClsid;
    hr = GetEncoderClsid(&imgClsid);
    if(hr == S_OK) 
    {
        wstring str(L"D:\\");
        str.append(CreateNewGuid());
        str.append(L".bmp");
        Status status = img->Save(str.c_str(), &imgClsid, NULL);
        if(status != Ok) 
        {
            hr = S_FALSE;
        }
    }
    return hr;
}

HRESULT SaveImage(HBITMAP hBmp) 
{
    Bitmap bmp(hBmp, NULL);
    return SaveImage(&bmp);
}



